<template>
  <a-drawer
    v-model:visible="isDrawer"
    :width="width"
    :title="title"
    unmountOnClose
    placement="right"
    :ok-loading="subLoading"
    :on-before-ok="formSubmit"
    @cancel="handleReset"
  >
    <a-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="80"
    >
      <a-form-item label="角色编码" field="roleCode">
        <a-input
          placeholder="请输入角色编码"
          v-model="formParams.roleCode"
          :disabled="formParams.roleId ? true : false"
        />
      </a-form-item>

      <a-form-item label="角色名称" field="roleName">
        <a-input placeholder="请输入角色名称" v-model="formParams.roleName" />
      </a-form-item>
      <a-form-item label="角色权限" field="permissionIds">
        <a-card>
          <a-space>
            <a-checkbox v-model="isSpread" @change="packHandle">展开/收起</a-checkbox>
            <a-checkbox v-model="isAll" @change="handleCheckAll">全选/全不选</a-checkbox>
          </a-space>
          <a-divider />
          <a-scrollbar style="height: 500px; overflow: auto">
            <a-tree
              ref="treeRef"
              checkable
              :fieldNames="{
                key: 'key',
                title: 'label',
                children: 'children',
              }"
              :virtual-scroll="true"
              :data="props.permissionList"
              :checked-keys="formParams.permissions"
              :expanded-keys="expandedKeys"
              @check="checkedTree"
              @expand="onExpandedKeys"
            />
          </a-scrollbar>
        </a-card>
      </a-form-item>
      <a-form-item label="备注" field="remark">
        <a-textarea placeholder="请输入备注" v-model="formParams.remark" />
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import type { formParamsType } from './types';

  import { addRole, editRole, roleInfo } from '@/api/system/role';

  const rules = {
    roleCode: {
      required: true,
      message: '角色编码不能为空',
      trigger: 'blur',
    },
    roleName: {
      required: true,
      message: '角色名称不能为空',
      trigger: 'blur',
    },
  };

  const emit = defineEmits(['change']);

  const props = defineProps({
    title: {
      type: String,
      default: '添加角色',
    },
    width: {
      type: Number,
      default: 450,
    },
    permissionList: {
      type: Array as PropType<any[]>,
      required: true,
    },
  });

  const defaultValueRef = () => ({
    roleId: null,
    roleName: '',
    roleCode: '',
    remark: '',
    permissions: [],
    permissionKeys: [],
  });

  const checkedKeys = ref<number[]>([]);
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);
  const isSpread = ref(false);
  const isAll = ref(false);
  const treeRef = ref();
  const expandedKeys = ref();

  const formParams = ref<formParamsType>(defaultValueRef());

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }

  function packHandle(value) {
    if (!value) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = props?.permissionList?.map((item: any) => item.key as string) as [];
    }
  }

  function handleCheckAll(value) {
    if (!value) {
      formParams.value.permissions = [];
    } else {
      formParams.value.permissions = getAllIds(
        props?.permissionList as { key: number; children: [] }[],
      );
    }
  }

  function getAllIds(list: { key: number; children: [] }[] = [], ids: number[] = []) {
    for (let item of list) {
      !ids.includes(item.key) && ids.push(item.key);
      if (item.children && item.children.length) getAllIds(item.children, ids);
    }
    return ids;
  }

  function checkedTree(keys: number[]) {
    console.log(keys);
    formParams.value.permissions = keys;
    checkedKeys.value = keys;
  }

  function openDrawer(roleId?) {
    if (roleId) {
      formParams.value.roleId = roleId;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function getPermissionKeys() {
    return treeRef.value?.getHalfCheckedNodes().map((item) => item.key);
  }

  function formSubmit(done) {
    formRef.value.validate((errors) => {
      if (errors) {
        Message.error('请填写完整信息');
        subLoading.value = false;
        return done(false);
      }
      formParams.value.permissionKeys = getPermissionKeys();
      if (formParams.value.roleId) {
        editRole(formParams.value)
          .then((_) => {
            Message.success('编辑成功');
            emit('change');
            handleReset();
            return done(true);
          })
          .catch(() => {
            return done(false);
          });
      } else {
        addRole(formParams.value)
          .then((_) => {
            Message.success('添加成功');
            emit('change');
            handleReset();
            return done(true);
          })
          .catch(() => {
            return done(false);
          });
      }
    });
  }

  function handleReset() {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    roleInfo({ roleId: formParams.value.roleId }).then((res) => {
      const info = {
        roleId: res.id,
        roleName: res.roleName,
        roleCode: res.roleCode,
        remark: res.remark,
        permissions: res.permissionIds,
        permissionKeys: res.permissionKeys,
      };
      formParams.value = info;
      isDrawer.value = true;
    });
  }

  onMounted(() => {});

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
